# -* - coding: UTF-8 -* -
#import sys
#reload(sys) 
#sys.setdefaultencoding('utf8')

import threading,string,os
import logging
from base_thread import Thread
from worker.thread import WorkerThread
from client_thread import ClientThread
from mysql_durable import *
from time import sleep
from task import *


#从外部队列读取消息放入内部对列
class WorkerFactory():  
	def __init__(self,worker_id,worker_path,worker_name,worker_count,serverFactory,clientFactory,notify_center,service_center,config):
		self.worker_id = worker_id
		self.worker_path = worker_path
		self.worker_name = worker_name
		self.worker_count = worker_count
		self.serverFactory=serverFactory
		self.clientFactory=clientFactory
		self.notify_center=notify_center
		self.service_center=service_center
		self.queue=Thread.Queue()
		self.durable=False#MysqlDurable(self.config)
		self.config=config
		self.threads=[]
		self.create()
	
		
	#生成队列
	def create(self):
		#queue队列
		self.service_center.register_queue(self.queue)
		
		self.queue_server=self.serverFactory.create(self.config,self.worker_name)
		self.worker=WorkerThread(self.queue_server,self.queue)
		self.name=self.worker.name				
		
		for i in range(self.worker_count):#10线程执行
			client=self.clientFactory.create(self.config)
			t = ClientThread(client,self.queue_server,self.notify_center,self.service_center,self.durable,self.queue)  
			self.threads.append(t)	
			
	#启动
	def start(self):
	
		self.__load()
		self.worker.start_thread()
		for t in self.threads:
			t.start_thread()
	
	#停止
	def stop(self):
		logging.info("queue Thread Stop!")
		self.worker.stop_thread()		
		for t in self.threads:
			t.stop_thread()
		self.__save()
	#停止
	def terminate(self):
		logging.info("queue Thread Terminate!")	
		self.worker.terminate()
		for t in self.threads:
			t.terminate()
			
	def __load(self):
		#读取历史订单
		#logging.info('读取SQL文件')
		
		logging.info('读取队列文件')
		path=os.path.join(self.worker_path,"queue_"+str(self.worker_id)+".txt")
		if os.path.isfile(path):
			f=open(path,'r')
			for line in f:
				if line.strip():
				   self.queue.put(line.strip())
			f.close()
		
	def __save(self):
		logging.info('保存队列文件')
		path=os.path.join(self.worker_path,"queue_"+str(self.worker_id)+".txt")
		#print(path)
		f=open(path,'w')
		while not self.queue.empty():
			line = self.queue.get()
			f.write(line+"\n")
		# 获取队列 
		f.close()
